<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Admin\ImageRequest;
use App\Services\QiniuImageUploadService;
use Illuminate\Http\Request;

class ImageController extends BaseController
{
    public function store(ImageRequest $request, QiniuImageUploadService $imageUploadService)
    {
        // \Log::info('调用了图片上传接口，ip:'.$request->getClientIp());
        $file = $request->file('image');
        /** @var UploadedFile $image */
        $type = $request->type;

        // 先判断有没有文件,有没有正常上传
        if ($request->hasFile('image') && $file->isValid()) {
            $path = $imageUploadService->save($file, $type, $this->getMaxWidth($type));
            $url = $imageUploadService->url;
            // \Log::info('图片上传成功:'.$url);
            return $this->response->array(['path' => $path, 'url' => $url]);
        }

        \Log::info('图片上传失败:' . $file->getErrorMessage());
        return $this->response->errorBadRequest('图片上传失败');
    }

    public function getMaxWidth($type)
    {
        $types = [
            'avatar' => 150,
            'face'   => 400, // 百度人脸比对要求人脸部分不小于100*100
        ];

        return $types[$type] ?? 800;
    }

    public function destroy(Request $request, QiniuImageUploadService $imageUploadService)
    {
        // 取到磁盘实例并删除图片，如果图片不存在，内部会抛404
        $imageUploadService->delete($request->image);
        return $this->response->noContent();
    }

    public function storeBase64(Request $request, QiniuImageUploadService $imageUploadService)
    {
        // \Log::info('调用了图片上传接口，ip:'.$request->getClientIp());


        /** @var resource|\GdImage|false $image */
        $image = $request->input('image');
        $type = $request->type;

        try {
            $path = $imageUploadService->saveBase64($image, $type, $this->getMaxWidth($type));
            $url = $imageUploadService->url;
            // \Log::info('图片上传成功:'.$url);

            return $this->response->array(['path' => $path, 'url' => $url]);
        } catch (\Exception $e) {
            \Log::info('图片上传失败:' . $e->getMessage());
            throw $e;
        }

    }
}
